package com.example.yls.demoa;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private Button btncreateDB;
    private Button btncreateTable;
    private Button btnInsert;
    private SQLiteDatabase db;
    private EditText editNo;
    private EditText editName;
    private EditText editAge;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btncreateDB=findViewById(R.id.btn_createDB);
        btncreateTable=findViewById(R.id.btn_createTable);
        btnInsert=findViewById(R.id.btn_insert);
        editNo=findViewById(R.id.edit_no);
        editName=findViewById(R.id.edit_name);
        editAge=findViewById(R.id.edit_age);

        btncreateDB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createOrOpenOB();
            }
        });
        btncreateTable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createTable();
            }
        });
        btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String no=editNo.getText().toString();
                String name=editName.getText().toString();
                int age=Integer.valueOf(editAge.getText().toString());
                insertStudent(no,name,age);
            }
        });
    }
    //插入学生数据
    private void insertStudent(String no,String name,int age) {
        if(db==null){
            createOrOpenOB();
        }
        //第一种 组装sql语句
        String sql="insert into student values(' " +no+ "'," +
                "' "+name+"','"+age+"')";
        db.execSQL(sql);


        //第二种 使用insert接口
        ContentValues values=new ContentValues();
        values.put("stuno",no);
        values.put("name",name);
        values.put("age",age);
        db.insert("student",null,values);
    }

    //创建学生表
    private void createTable() {
        if(db==null){
            createOrOpenOB();
        }
        String sql="create table if not exists student " +
                "(stuno varchar(20),name varchar(20),age int)";
        db.execSQL(sql);


    }

    //创建数据库
    private void createOrOpenOB() {
        String path=getFilesDir().getAbsolutePath()+ File.separator+"stu.db";
        Log.e("MainActivity"," path= "+path);

        db= SQLiteDatabase.openOrCreateDatabase(path,null);
    }
}
